package com.da.lon.wang.xlg;

import android.app.Activity;
import android.app.Application;
import android.content.Context;
import android.content.Intent;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.support.multidex.MultiDex;
import android.view.inputmethod.InputMethodManager;
import android.widget.EditText;
import android.widget.ImageView;

import com.bumptech.glide.Glide;
import com.da.lon.wang.xlg.bean.CheckInfoResultBean.cart_result;
import com.da.lon.wang.xlg.bean.DetailBean.FhName;
import com.da.lon.wang.xlg.bean.DetailBean.NomeList;
import com.da.lon.wang.xlg.bean.HomeResultBean.HomeItemContentBean;
import com.da.lon.wang.xlg.bean.ResultSearchBean.ResultSearchListBean.SearchResultCategory;
import com.da.lon.wang.xlg.bean.ResultSearchBean.ResultSearchListBean.SearchResultOther;
import com.da.lon.wang.xlg.constants.PreferencesConfig;
import com.da.lon.wang.xlg.imgupload.ImageInfo;
import com.da.lon.wang.xlg.util.PreferenceUtils;
import com.da.lon.wang.xlg.util.WebViewUtil;
import com.nostra13.universalimageloader.cache.disc.naming.Md5FileNameGenerator;
import com.nostra13.universalimageloader.core.ImageLoader;
import com.nostra13.universalimageloader.core.ImageLoaderConfiguration;
import com.nostra13.universalimageloader.core.assist.QueueProcessingType;
import com.osell.selection.util.DeviceUuidFactory;
import com.osell.selection.util.LocaleHelper;
import com.squareup.picasso.Picasso;
import com.tencent.mm.sdk.openapi.IWXAPI;
import com.tencent.mm.sdk.openapi.WXAPIFactory;

import net.tsz.afinal.FinalHttp;

import java.io.File;
import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;
import java.util.Timer;
import java.util.TimerTask;

import cn.jpush.android.api.JPushInterface;

public class MyApplication extends Application {

    private static final String TAG = "MyApplication";
    public static MyApplication mInstance;
    public static IWXAPI api;
    public static FinalHttp finalHttp;
    public static int is_skulist_enter_capture;
    private static List<Activity> xlgActivitys = new LinkedList<>();
    private static List<String> home_item_type = new ArrayList<>();
    private static WebViewUtil webViewUtil;
    private static boolean myoption = false;
    public List<ImageInfo> imageInfos;
    public double latitude = 0.0, longitude = 0.0;
    public ArrayList<SearchResultOther> otherlist;
    public ArrayList<SearchResultCategory> categorylist;
    public ArrayList<FhName> fhnamelist;
    public ArrayList<NomeList> nomelist;
    public ArrayList<cart_result> datas;
    public ArrayList<HomeItemContentBean> productList;
    public String price_small;
    // private static ImageCacheUtil imageCacheUtil;
    public String price_hight;
    public String tuikuan_message_url;
    public Activity skulist_activity;

    public static List<String> getHome_item_type() {
        return home_item_type;
    }

    public static void setHome_item_type(List<String> home_item_type) {
        MyApplication.home_item_type = home_item_type;
    }

    public static int getIs_skulist_enter_capture() {
        return is_skulist_enter_capture;
    }

    public static void setIs_skulist_enter_capture(int is_skulist_enter_capture) {
        MyApplication.is_skulist_enter_capture = is_skulist_enter_capture;
    }

    public static List<Activity> getXlgActivitys() {
        return xlgActivitys;
    }

    public static void setXlgActivitys(List<Activity> xlgActivitys) {
        MyApplication.xlgActivitys = xlgActivitys;
    }

    public static boolean isMyoption() {
        return myoption;
    }

    public static void setMyoption(boolean myoption) {
        MyApplication.myoption = myoption;
    }

    public static FinalHttp getHttp() {
        if (finalHttp == null) {
            finalHttp = new FinalHttp();
        }
        return finalHttp;
    }

    public static WebViewUtil getWebViewUtil() {
        return webViewUtil;
    }

    public static void setWebViewUtil(WebViewUtil webViewUtil) {
        MyApplication.webViewUtil = webViewUtil;
    }

    public static MyApplication getInstance() {
        return mInstance;
    }

    public static void initImageLoader(Context context) {

        ImageLoaderConfiguration config = new ImageLoaderConfiguration.Builder(
                context).threadPriority(Thread.NORM_PRIORITY - 2)
                .denyCacheImageMultipleSizesInMemory()
                .discCacheFileNameGenerator(new Md5FileNameGenerator())
                .tasksProcessingOrder(QueueProcessingType.LIFO)

                .build();
        ImageLoader.getInstance().init(config);
    }

    public static void addActivity(Activity activity) {
        xlgActivitys.add(activity);
    }

    public static void clearActivityList() {
        for (Activity activity : xlgActivitys) {
            activity.finish();
        }
        xlgActivitys.clear();
    }

    public static void hideInputWindow(EditText editText, Context context) {
        try {
            if (editText != null
                    && context != null
                    && (editText.getContext()
                    .getSystemService(Context.INPUT_METHOD_SERVICE)) != null
                    && ((Activity) context).getCurrentFocus() != null) {
                ((InputMethodManager) editText.getContext().getSystemService(
                        Context.INPUT_METHOD_SERVICE))
                        .hideSoftInputFromWindow(((Activity) context)
                                        .getCurrentFocus().getWindowToken(),
                                InputMethodManager.HIDE_NOT_ALWAYS);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public static void showinputwindow(final EditText editText, Context context) {
        try {
            Timer timer = new Timer();
            timer.schedule(new TimerTask() {

                public void run() {
                    InputMethodManager inputManager = (InputMethodManager) editText
                            .getContext().getSystemService(
                                    Context.INPUT_METHOD_SERVICE);
                    inputManager.showSoftInput(editText, 0);
                }

            }, 998);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public static String getUserId() {
        return PreferenceUtils.getInstance().getSettingStr(
                PreferencesConfig.USER_ID, "");
    }

    public static String getDeviceId() {
        return new DeviceUuidFactory(MyApplication.getInstance()).getDeviceUuid().toString();
    }

    public static String getStoreName() {
        return PreferenceUtils.getInstance().getSettingStr(
                PreferencesConfig.STORE_NAME, "");
    }

    public static String getUserName() {
        return PreferenceUtils.getInstance().getSettingStr(
                PreferencesConfig.USER_NAME, "");
    }

    public static String getUserKey() {
        return PreferenceUtils.getInstance().getSettingStr(
                PreferencesConfig.USER_KEY, "");
    }

    public static String getShopId() {
        return PreferenceUtils.getInstance().getSettingStr(
                PreferencesConfig.STORE_ID, "");
    }

    public static boolean isWXAppInstalledAndSupported() {
        boolean sIsWXAppInstalledAndSupported = false;
        try {
            sIsWXAppInstalledAndSupported = api.isWXAppInstalled()
                    && api.isWXAppSupportAPI();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return sIsWXAppInstalledAndSupported;
    }

    public static void loadImageByPicasso(Context context, String path,
                                          File file, ImageView imageView, int width, int height, int type) {
        if (context != null && imageView != null) {
            if (null != path && !path.trim().equals("") && width == 0
                    && height == 0 && type == 0) {
                Picasso.with(context).load(path)
                        .placeholder(R.drawable.inset_place_holder_logo)
                        .error(R.drawable.inset_place_holder_logo).into(imageView);

            } else if (null != path && !path.trim().equals("") && width == 0
                    && height == 0 && type == 1) {
                Picasso.with(context).load(path)
                        .placeholder(R.drawable.inset_place_holder_logo_small)
                        .error(R.drawable.inset_place_holder_logo_small).into(imageView);
            } else if (null != path && !path.trim().equals("") && width > 0
                    && height > 0 && type == 0) {
                Picasso.with(context).load(path).resize(width, height)
                        .placeholder(R.drawable.inset_place_holder_logo)
                        .error(R.drawable.inset_place_holder_logo).into(imageView);
            } else if (null != path && !path.trim().equals("") && width > 0
                    && height > 0 && type == 1) {
                Picasso.with(context).load(path).resize(width, height)
                        .placeholder(R.drawable.inset_place_holder_logo_small)
                        .error(R.drawable.inset_place_holder_logo_small).into(imageView);
            } else if (null != file && width == 0 && height == 0 && type == 0) {
                Picasso.with(context).load(file)
                        .placeholder(R.drawable.inset_place_holder_logo)
                        .error(R.drawable.inset_place_holder_logo).into(imageView);

            } else if (null != file && width == 0 && height == 0 && type == 1) {
                Picasso.with(context).load(file)
                        .placeholder(R.drawable.inset_place_holder_logo_small)
                        .error(R.drawable.inset_place_holder_logo_small).into(imageView);
            } else if (null != file && width > 0 && height > 0 && type == 0) {
                Picasso.with(context).load(file).resize(width, height)
                        .placeholder(R.drawable.inset_place_holder_logo)
                        .error(R.drawable.inset_place_holder_logo).into(imageView);
            } else if (null != file && width > 0 && height > 0 && type == 1) {
                Picasso.with(context).load(file).resize(width, height)
                        .placeholder(R.drawable.inset_place_holder_logo_small)
                        .error(R.drawable.inset_place_holder_logo_small).into(imageView);
            } else if (null != path && !path.trim().equals("") && width == 0
                    && height == 0 && type == 2) {
                Glide.with(context).load(path)
                        .placeholder(R.drawable.inset_place_holder_logo)
                        .error(R.drawable.inset_place_holder_logo).into(imageView);
            }
        }
    }

    public static boolean isNetworkAvailable(Context context) {
        // 获取手机所有连接管理对象（包括对wi-fi,net等连接的管理）
        ConnectivityManager connectivityManager = (ConnectivityManager) context
                .getSystemService(Context.CONNECTIVITY_SERVICE);
        if (connectivityManager == null) {
            return false;
        } else {
            // 获取NetworkInfo对象
            NetworkInfo[] networkInfo = connectivityManager.getAllNetworkInfo();

            if (networkInfo != null && networkInfo.length > 0) {
                for (int i = 0; i < networkInfo.length; i++) {
                    // 判断当前网络状态是否为连接状态
                    if (networkInfo[i].getState() == NetworkInfo.State.CONNECTED) {
                        return true;
                    }
                }
            }
        }
        return false;
    }

    public static void openSystemSetting(Context context) {
        try {
            if (android.os.Build.VERSION.SDK_INT > 13
                    && android.provider.Settings.ACTION_SETTINGS != null
                    && !"".equals(android.provider.Settings.ACTION_SETTINGS)) {
                context.startActivity(new Intent(
                        android.provider.Settings.ACTION_SETTINGS));
            } else {
                if (android.provider.Settings.ACTION_WIRELESS_SETTINGS != null
                        && !"".equals(android.provider.Settings.ACTION_WIRELESS_SETTINGS))
                    context.startActivity(new Intent(
                            android.provider.Settings.ACTION_WIRELESS_SETTINGS));
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public static void addHomeType() {
        home_item_type.add("homePageRollCategory");
        home_item_type.add("homePageRollAds");
        home_item_type.add("homePageThemeActivities");
        home_item_type.add("homePageSpaceRow");
        home_item_type.add("homePageSeckillGoods");
        home_item_type.add("homePageHeader");
        home_item_type.add("homePageMultipleProductImage");
        home_item_type.add("homePageSingleAd");
        home_item_type.add("homePageSingleProduct");
    }

    @Override
    public void onCreate() {

        mInstance = this;
        is_skulist_enter_capture = 0;
        //api = WXAPIFactory.createWXAPI(this, "wxfa24e93c38166a8d", true);
        api = WXAPIFactory.createWXAPI(this, null);
        api.registerApp("wxfa24e93c38166a8d");

        PreferenceUtils.init(this);
        initImageLoader(getApplicationContext());
        imageInfos = new ArrayList<>();

        webViewUtil = new WebViewUtil(getApplicationContext());
        finalHttp = new FinalHttp();

        addHomeType();

        JPushInterface.setDebugMode(true);
        JPushInterface.init(this);

        super.onCreate();
    }

    @Override
    protected void attachBaseContext(Context base) {
        super.attachBaseContext(LocaleHelper.onAttach(base));
        MultiDex.install(this);
    }

    public ArrayList<NomeList> getNomelist() {
        return nomelist;
    }

    public void setNomelist(ArrayList<NomeList> nomelist) {
        this.nomelist = nomelist;
    }

    public Activity getSkulist_activity() {
        return skulist_activity;
    }

    public void setSkulist_activity(Activity skulist_activity) {
        this.skulist_activity = skulist_activity;
    }

    public ArrayList<HomeItemContentBean> getProductList() {
        return productList;
    }

    public void setProductList(ArrayList<HomeItemContentBean> productList) {
        this.productList = productList;
    }

    public String getTuikuan_message_url() {
        return tuikuan_message_url;
    }

    public void setTuikuan_message_url(String tuikuan_message_url) {
        this.tuikuan_message_url = tuikuan_message_url;
    }

    public ArrayList<SearchResultOther> getOtherlist() {
        return otherlist;
    }

    public void setOtherlist(ArrayList<SearchResultOther> otherlist) {
        this.otherlist = otherlist;
    }

    public ArrayList<SearchResultCategory> getCategorylist() {
        return categorylist;
    }

    public void setCategorylist(ArrayList<SearchResultCategory> categorylist) {
        this.categorylist = categorylist;
    }

    public ArrayList<FhName> getFhnamelist() {
        return fhnamelist;
    }

    public void setFhnamelist(ArrayList<FhName> fhnamelist) {
        this.fhnamelist = fhnamelist;
    }

    public String getPrice_small() {
        return price_small;
    }

    public void setPrice_small(String price_small) {
        this.price_small = price_small;
    }

    public String getPrice_hight() {
        return price_hight;
    }

    public void setPrice_hight(String price_hight) {
        this.price_hight = price_hight;
    }

    public double getLongitude() {
        return longitude;
    }

    public void setLongitude(double longitude) {
        this.longitude = longitude;
    }

    public double getLatitude() {
        return latitude;
    }

    public void setLatitude(double latitude) {
        this.latitude = latitude;
    }

    public ArrayList<cart_result> getDatas() {
        return datas;
    }

    public void setDatas(ArrayList<cart_result> datas) {
        this.datas = datas;
    }

    public void addImageInfo(ImageInfo imageInfo) {
        imageInfos.add(imageInfo);
    }

    public void deleteImageInfo(String path) {
        for (int i = 0; i < imageInfos.size(); i++) {
            ImageInfo imageInfo = imageInfos.get(i);
            if (imageInfo.path.endsWith(path)) {
                imageInfos.remove(imageInfo);
                break;
            }
        }
    }

    public int getImageInfosSize() {
        if (imageInfos != null) {
            return imageInfos.size();
        } else {
            return 0;
        }
    }

    public void deleteAllImageInfos() {
        if (imageInfos != null && imageInfos.size() > 0) {
            imageInfos.clear();
        }
    }

}
